// 封装购物车模块

import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {useUserStore} from './user'
import {addCartAPI, getCartAPI, delcartAPI, mergeCartAPI, changeAllSelected, changeCountAPI} from '@/apis/cart'
import type {Ref} from "vue";

/**
 *    id:商品id
 name:商品名称
 picture:商品图片
 count:商品数量
 skuId:商品skuId,
 price:商品金额
 attrsText:商品sku文本
 selected:商品是否选中
 --------------------------
 */
function clone(target: any[], cloneObj: any[]) {
    for (let i = 0; i < cloneObj.length; i++) {
        target[i] = cloneObj[i]
    }
}

export const useCartStore = defineStore('cart',
    () => {

        const userStore = useUserStore()
        // 1. 定义state - cartList
        const _cartList = ref([])
        const cartList: { value: Array<any> } = new Proxy<{ value: Array<any> }>(_cartList, {
            set: (target: any, prop: string, newValue: any) => {
                const setSuccess = prop === 'value'
                if (setSuccess) {
                    //target[prop].length = 0;
                    if (newValue.length > 0) {
                        clone(target[prop], newValue)
                    }
                } else
                    target[prop] = newValue
                return true
            }
        })
        // if(userStore.user.token){
        //   const res = await getCartAPI()
        //   cartList.value = res.data.result
        // }
        // 2. 定义action - addCart
        const addCart = async (goods) => {
            // 添加购物车操作
            // 已添加过 - count + 1
            // 没有添加过 - 直接push
            // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
            if (userStore.user.token) {
                await addCartAPI({skuId: goods.skuId, count: goods.count})
                const res = await getCartAPI()
                cartList.value = res.data.result
            } else {
                const item = cartList.value.find((item) => goods.skuId === item.skuId)
                if (item) {
                    // 找到了
                    item.count += goods.count
                } else {
                    // 没找到
                    cartList.value.push(goods)
                }
            }
            //持久化
            localStorage.setItem('XtxCart', JSON.stringify(cartList.value))
        }
        //持久化cart
        const initCart = async () => {
            if (userStore.user.token) {
                const res = await getCartAPI()
                if(res) cartList.value = res.data.result
                localStorage.setItem('XtxCart', JSON.stringify(cartList.value))
            } else {
                const cartData = localStorage.getItem('XtxCart')
                if (cartData) {
                    cartList.value = JSON.parse(cartData)
                } else {
                    cartList.value = []
                }
            }

        }
        //删除商品
        const delCart = async (skuIdArr) => {
            if (skuIdArr) {
                if (userStore.user.token) {
                    await delcartAPI(skuIdArr)
                    const res = await getCartAPI()
                    cartList.value = res.data.result
                    console.log(res)
                } else {
                    skuIdArr.forEach(item => {
                        const index = cartList.value.findIndex(i => i.skuId === item)
                        cartList.value.splice(index, 1)
                    })
                }
                localStorage.setItem('XtxCart', JSON.stringify(cartList.value))
            }
        }
        //修改商品是否选中
        const updataChecke = async (checked, skuId) => {
            //全部选中状态切换
            if (!skuId) {
                cartList.value.forEach(item => {
                    item.selected = checked
                });
                if (userStore.user.token) {
                    if (cartList.value.length > 1) {
                        const ids = cartList.value.map(({skuId}) => skuId);
                        const res = await changeAllSelected(checked, ids)
                        console.log(res)
                    }
                }
                localStorage.setItem('XtxCart', JSON.stringify(cartList.value))
            }
            //单个切换
            const index = cartList.value.findIndex(item => item.skuId === skuId)
            // console.log(index)
            if (index != -1) {
                if (userStore.user.token) {
                    await changeCountAPI(skuId, checked, cartList.value[index].count)
                } else {
                    cartList.value[index].selected = checked
                }
                localStorage.setItem('XtxCart', JSON.stringify(cartList.value))
            }
        }

        interface MergeCartParams {
            skuId: String,
            selected: Boolean,
            count: Number
        }

        const mergeCart = async () => {
            let data = localStorage.getItem('XtxCart')
            data = JSON.parse(data)
            console.log('data', data)
            console.log('是否为数组', Array.isArray(data))
            if (data) {
                data = data.map(({skuId, selected, count}: MergeCartParams) => ({
                    skuId,
                    selected,
                    count
                }))
                await mergeCartAPI(data)
            }
            const res = await getCartAPI()
            cartList.value = res.data.result
            console.log(cartList.value)
        }
        //退出登录
        const logOut = () => {
            cartList.value.length = 0
            localStorage.removeItem('XtxCart')
        }
        return {
            cartList,
            addCart,
            initCart,
            delCart,
            updataChecke,
            mergeCart,
            logOut
        }
    })